<?php
class MHtmlButtonColumn extends MHtmlColumn {
    const DELETE_BUTTON = 'delete';
    const UPDATE_BUTTON = 'update';
    const CREATE_BUTTON = 'create';
    
    private $_buttons = array();
    private $_headerButton;
    
    public function __construct($table, $buttons = array()) {
        parent::__construct($table);
        $this->_buttons = $buttons;
    }
    
    public function setHeaderButton($options = array()){
        $this->_headerButton = $options;
    }
    
    public function renderHeader(){
        $return = '';
        if (array_key_exists(self::CREATE_BUTTON, $this->_buttons)){
            $return .= MHtml::tag('th', array(), MHtml::tag('a', $this->_buttons[self::CREATE_BUTTON], (isset($this->_buttons[self::CREATE_BUTTON]['content']))?$this->_buttons[self::CREATE_BUTTON]['content']:false));
        } else if (isset ($this->_headerButton) && !empty ($this->_headerButton)) {
            $return .= MHtml::tag('th', array(), MHtml::tag('a', $this->_headerButton));
        } else {
            $return .= MHtml::tag('th', array());
        }
        return $return;
    }
    
    public function renderBody($rowIndex){
        $buttons = '';
        foreach ($this->_buttons as $key=>$options) {
            if ($key !== self::CREATE_BUTTON){
                $matches = array();
                if (preg_match_all('#\{(.+)\}#isU', $options['href'], $matches)>0){
                    $attributes = $this->_table->getRow($rowIndex)->attributes();
                    $count = count($matches[0]);
                    for ($i = 0; $i < $count; $i++){
                        $attribute = $matches[1][$i];
                        if (array_key_exists($attribute, $attributes))
                            $options['href'] = str_ireplace($matches[0][$i], $attributes[$attribute], $options['href']);
                    }
                    $buttons .= MHtml::tag('a', $options, (isset ($options['content'])?$options['content']:false));
                } else {
                    $buttons .= MHtml::tag('a', $options, (isset ($options['content'])?$options['content']:false));
                }
            }
        }
        return MHtml::tag('td', $this->_htmlOptions, $buttons);
    }
}
?>
